#include "common.h"



class UdpServer
{
  public:
    // 创建服务器对象时，需要指定它的端口号
    UdpServer(const unsigned short port)
      :_port(port)
      ,_sockfd(-1)
    {}

    ~UdpServer()
    {
      if(_sockfd >= 0)
      {
        close(_sockfd);
      }
    }


  // 创建套接字（申请网络设备文件）+ 绑定 socket 地址
  void InitUdpServer()
  {
    if((_sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
      cerr << "socket error" << endl;
      return;
    }
    cout << "Server socket(...) sucess" << endl; 
  
    struct sockaddr_in local;
    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(_port);
    local.sin_addr.s_addr = htonl(INADDR_ANY);
    
    if(bind(_sockfd, (struct sockaddr*)&local, sizeof(local)) == -1)
    {
      cerr << "bind error" << endl;
      return;
    }
    cout << "Server bind(...) sucess" << endl;
  }

  void LoopServer()
  {
    char buffer[SIZE] = {0};
    socklen_t len = sizeof(len);
    struct sockaddr_in peer;
     
    while(true)
    {
      ssize_t size = recvfrom(_sockfd, buffer, SIZE - 1, 0, (struct sockaddr*)&peer, &len);
      if(size >= 0)
      {
        buffer[size] = '\0';
        unsigned short port = ntohs(peer.sin_port);
        string ip(inet_ntoa(peer.sin_addr));

        cout << '[' << ip << ' ' << port << "]# " << buffer << endl;
      }
      else 
      {
        cerr << "recvfrom error" << endl;
      }
    }
  }


  private:
    unsigned short _port;
    unsigned short _sockfd;
};
